package net.daum.webtoon.android.io;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

import net.daum.webtoon.android.session.SessionManager;
import net.daum.webtoon.android.util.Logger;

import org.json.JSONObject;

import android.content.Context;

public class RESTFulClient {

	private static final String TAG = RESTFulClient.class.getSimpleName();

	private static final int READ_TIME_OUT = 10000;

	private static final String URL_DAUM_WEB_TOON_FORMAT = "http://cartoon.media.daum.net/data/webtoon/list_by_option?genre=&category=&highScore=&minScore=&webtoonStatus=&hotIssue=&page_no=%d&page_size=%d&timestamp=%d";
	private static final String URL_DAUM_WEB_TOON_DETAIL_LIST_FORMAT = "http://m.cartoon.media.daum.net/data/mobile/webtoon/list_episode_by_nickname?nickname=%s&page_no=%d&page_size=%d&%d";

	private static final String URL_DAUM_WEB_TOON_VIEW_COOKIE_FORMAT = "http://cartoon.media.daum.net/webtoon/viewer/%d";
	private static final String URL_DAUM_WEB_TOON_VIEW_COMIC_FORMAT = "http://cartoon.media.daum.net/webtoon/viewer_images.js?webtoon_episode_id=%d";

	/**
	 * search auto fill
	 */
	private static final String URL_DAUM_WEB_TOON_AUTO_FILL_SEARCH = "http://m.cartoon.media.daum.net/m/keyword?category=mobile_webtoon&q=%s&mod=json&code=utf_in_out";
	/**
	 * search url
	 */
	private static final String URL_DAUM_WEB_TOON_SEARCH = "http://m.cartoon.media.daum.net/data/mobile/search?q=%s&type=webtoon&page_no=%d&page_size=%d&%d";

	private Context context;

	public RESTFulClient() {
	}

	public RESTFulClient(Context context) {
		this.context = context;
	}

	public JSONObject getDaumWebToon(int page) throws Exception {
		return getDaumWebToon(page, 30);
	}

	public JSONObject getDaumWebToon(int page, int size) throws Exception {
		JSONObject data = null;
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_FORMAT, page, size,
				System.currentTimeMillis()));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		initPostHttpURLConnection(httpURLConnection);
		try {
			httpURLConnection.connect();
			int status = httpURLConnection.getResponseCode();
			switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(
						httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				return data = new JSONObject(sb.toString());
			}
		} finally {
			httpURLConnection.disconnect();
		}
		return data;
	}

	public JSONObject getWebToonListEpisodeByNickName(String nickName)
			throws Exception {
		return getWebToonListEpisodeByNickName(nickName, 1, 10);
	}

	public JSONObject getWebToonListEpisodeByNickName(String nickName,
			int page, int size) throws Exception {
		JSONObject data = null;
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_DETAIL_LIST_FORMAT,
				nickName, page, size, System.currentTimeMillis()));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		initGetHttpURLConnection(httpURLConnection);
		try {
			httpURLConnection.connect();
			int status = httpURLConnection.getResponseCode();
			switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(
						httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				return data = new JSONObject(sb.toString());
			}
		} finally {
			httpURLConnection.disconnect();
		}
		return data;
	}

	/**
	 * 
	 * @param episodeId
	 *            such as 18971
	 * @return
	 * @throws Exception
	 */
	public JSONObject getWebToonImgUrlByEpisodeId(long episodeId)
			throws Exception {
		JSONObject data = null;
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_VIEW_COOKIE_FORMAT,
				episodeId));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		initGetHttpURLConnection(httpURLConnection);
		String value = null;
		try {
			httpURLConnection.connect();
			for (String key : httpURLConnection.getHeaderFields().keySet()) {
				if ("Set-Cookie".equalsIgnoreCase(key)) {
					value = httpURLConnection.getHeaderFields().get(key)
							.toString();
				}
			}
			url = new URL(String.format(URL_DAUM_WEB_TOON_VIEW_COMIC_FORMAT,
					episodeId));
			httpURLConnection = (HttpURLConnection) url.openConnection();
			initPostHttpURLConnection(httpURLConnection);
			httpURLConnection.addRequestProperty("Cookie", value);

			httpURLConnection.connect();
			int status = httpURLConnection.getResponseCode();
			switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(
						httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				return data = new JSONObject(sb.toString());
			}
		} finally {
			httpURLConnection.disconnect();
		}
		return data;
	}

	public JSONObject getWebToonSearchKeyword(String keyword) throws Exception {
		JSONObject data = null;
		String encodedKeyword = URLEncoder.encode(keyword, "UTF-8");
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_AUTO_FILL_SEARCH,
				encodedKeyword));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		initGetHttpURLConnection(httpURLConnection);
		try {
			httpURLConnection.connect();
			int status = httpURLConnection.getResponseCode();
			switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(
						httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				Logger.i(TAG, sb.toString());
				return data = new JSONObject(sb.toString());
			}
		} finally {
			httpURLConnection.disconnect();
		}
		return data;
	}

	public JSONObject getWebToonSearch(String keyword) throws Exception {
		return getWebToonSearch(keyword, 1, 10);
	}

	public JSONObject getWebToonSearch(String keyword, int page, int pageSize)
			throws Exception {
		JSONObject data = null;
		String encodedKeyword = URLEncoder.encode(keyword, "UTF-8");
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_SEARCH,
				encodedKeyword, page, pageSize, System.currentTimeMillis()));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		initGetHttpURLConnection(httpURLConnection);
		try {
			httpURLConnection.connect();
			int status = httpURLConnection.getResponseCode();
			switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(
						httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				return data = new JSONObject(sb.toString());
			}
		} finally {
			httpURLConnection.disconnect();
		}
		return data;
	}

	private HttpURLConnection initPostHttpURLConnection(
			HttpURLConnection httpURLConnection) throws ProtocolException {
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		return initHttpURLConnection(httpURLConnection);
	}

	private HttpURLConnection initGetHttpURLConnection(
			HttpURLConnection httpURLConnection) throws ProtocolException {
		httpURLConnection.setRequestMethod("GET");
		return initHttpURLConnection(httpURLConnection);
	}

	private HttpURLConnection initHttpURLConnection(
			HttpURLConnection httpURLConnection) {
		httpURLConnection.setReadTimeout(READ_TIME_OUT);
		return httpURLConnection;
	}

}
